package util

import (
	"github.com/axgle/mahonia"
	"github.com/gocolly/colly"
	"github.com/gocolly/colly/debug"
	"log"
	"net/http"
	"strings"
)

func IsEmpty(str string) bool {

	return len(str) == 0
}

func IsNotEmpty(str string) bool {
	return !IsEmpty(str)
}

func ExistStr(str string, switchStr string) bool {
	if IsEmpty(str) {
		return false
	}

	return strings.Index(str, switchStr) > -1
}

func CreateColly(url string, responseFun colly.ResponseCallback, onHtmlFun func(c *colly.Collector), cookeMap map[string]string) *colly.Collector {
	c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"),
		colly.MaxDepth(1),
		colly.Debugger(&debug.LogDebugger{}))

	c.OnResponse(func(response *colly.Response) {
		html := ""
		if nil != response.Body {
			html = string(response.Body)

			html = mahonia.NewDecoder("gbk").ConvertString(html)

		}
		//log.Println("body--->" + html)
		if nil != responseFun {
			responseFun(response)
		}
	})

	if nil != cookeMap {
		var cookies []*http.Cookie
		for country := range cookeMap {
			cookie := &http.Cookie{
				Name:  country,
				Value: cookeMap[country],
			}

			cookies = append(cookies, cookie)

		}
		c.SetCookies(url, cookies)
	}

	if nil != onHtmlFun {
		onHtmlFun(c)
	}

	c.OnError(func(r *colly.Response, err error) {
		log.Println("Request URL:", r.Request.URL, "failed with response:", r, "\nError:", err)
	})

	c.Visit(url)

	// 等待爬虫结束
	c.Wait()

	return c
}
